import React, { Component } from 'react'
import { StyleSheet } from 'react-native'
import { ScaleS, HEIGHT } from 'src/utils/ScreenUtil'
import PropTypes from 'prop-types'
import CustomModal from '../modal/CustomModal'
import Animated, { Easing } from 'react-native-reanimated'

const { Value, timing } = Animated
export default (transY = parseInt(HEIGHT * 2 / 3)) => {
  return (WrappedComponent) => {
    class WrapWithPopModal extends Component {
      constructor (props) {
        super(props)
        this._transY = new Value(parseInt(transY))
        this._config = {
          duration: 200,
          toValue: 0,
          easing: Easing.inOut(Easing.ease)
        }
        this._config2 = {
          duration: 200,
          toValue: new Value(parseInt(transY)),
          easing: Easing.inOut(Easing.ease)
        }
        this.state = {
          visible: props.visible
        }
      }

      render () {
        const { visible } = this.state
        const { visible: visibleProp, onDismiss, onRequestClose, ...others } = this.props
        return (
          <CustomModal
            visible={visible}
            // onDismiss={onDismiss}
            onShow={this.onShow}
            onRequestClose={onRequestClose}
          >
            <Animated.View style={[styles.animateView, { transform: [{ translateY: this._transY }] }]}>
              <WrappedComponent {...others}/>
            </Animated.View>
          </CustomModal>
        )
      }

      componentDidUpdate (prevProps, prevState) {
        const { visible: prevVisible } = prevProps
        const { visible: nextVisible, onDismiss } = this.props
        if (nextVisible !== prevVisible) {
          if (nextVisible) {
            this.setState({ visible: true })
          } else {
            this.closePopModal().then(() => {
              this.setState({ visible: false }, () => {
                setTimeout(() => {
                  onDismiss && onDismiss()
                }, 100)
              })
            })
          }
        }
      }

      onShow = () => {
        timing(this._transY, this._config).start()
      }

      closePopModal = () => {
        return new Promise((resolve) => {
          timing(this._transY, this._config2).start(({ finished }) => {
            finished && resolve()
          })
        })
      }
    }

    WrapWithPopModal.propTypes = {
      visible: PropTypes.bool.isRequired,
      onDismiss: PropTypes.func,
      onRequestClose: PropTypes.func.isRequired
    }
    WrapWithPopModal.defaultProps = {
      visible: false
    }
    return WrapWithPopModal
  }
}

const styles = StyleSheet.create({
  animateView: {
    position: 'absolute',
    bottom: ScaleS(7),
    left: ScaleS(7),
    right: ScaleS(7),
    backgroundColor: 'transparent'
  }
})
